const q = require('./q')

function uploadFile(files = [], args = {}) {
  let self = this;
  let datas = [];
  let i = 0;
  return q.Promise((resolve, reject) => {
    let upload = function (files) {
      let len = files.length - 1
      let file = files.shift();
      if(typeof file == 'object'){
        datas.push(file);
        ++i;
        if (files.length > 0) {
          upload(files)
        } else {
          resolve(datas)
        }
        return;
      }
      wx.uploadFile({
        url: "http://172.16.0.70:3000/api/users/update_me",
        filePath: file,
        name: 'image',
        formData: {},
        header: {
          'content-type': "multipart/form-data",
          'Authorization': wx.getStorageSync('sale_token')
        },
        success(res) {
          let data = JSON.parse(res.data);
          if(args.bool) {
            datas.push({ image: data.image, image_type: i});
            ++i;
          } else {
            datas.push(data.image);
          }
        },
        fail(err) {
        },
        complete(cc) {
          if (files.length > 0) {
            upload(files)
          } else {
            resolve(datas)
          }
        }
      })
    }
    if (files.length > 0) {
      upload(files);
    } else { resolve([]); }

  })
}

function previewImage(...args) {
  formatUrl(args).then(datas => {
    wx.previewImage({
      current: datas.src,
      urls: datas.imgs
    })
  })
}

function formatUrl(args) {
  let datas = {
    src: args[0],
    imgs: []
  }
  return q.Promise((resolve, reject) => {
    args[0].imgs.map(v => {
      datas.imgs.push(v.image)
    })
    resolve(datas)
  })
}

module.exports = {
  uploadFile: uploadFile,
  previewImage: previewImage
}
